import { AnyAction, Reducer } from 'redux';

import { EffectsCommandMap } from 'dva';

import { fetchValidation } from '@/utils';
import {
    queryCheckUser,
    queryLogisList,
    queryOtherLogisList,
    queryLogisDetail,
} from './service';


export type Effect = (
    action: AnyAction,
    effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
    namespace: string;
    state: {};
    effects: {
        checkUserPerm: Effect;
        fetchLogisList: Effect;
        fetchOtherLogisList: Effect;
        selectLogis: Effect;
    };
    reducers: {
        saveLogis: Reducer;
        show: Reducer;
    };
}

const Model: ModelType = {
    namespace: 'ocrCheckLogis',

    state: {
        logisList: [],
        dataInfo: {
            uncheckCount: 0,
            checkedCount: 0,
        },
        hasCheck: false,
    },

    effects: {
        * checkUserPerm({ payload }, { call, put }) {
            const response = yield call(queryCheckUser, payload);
            const data = fetchValidation(response);
            if (data) {
                const { body } = data;
                if (body.is_root !== 1) {
                    yield data && put({
                        type: 'fetchOtherLogisList',
                        payload: { djy: 20, ywc: 30 },
                    });
                }
            }
        },

        /** 超管 */
        * fetchLogisList({ payload }, { call, put }) {
            const response = yield call(queryLogisList, payload);
            const data = fetchValidation(response);
            yield data && put({
                type: 'saveLogis',
                payload: data.body,
            });
        },

        /** 非超管 */
        * fetchOtherLogisList({ payload }, { call, put }) {
            const response = yield call(queryOtherLogisList, payload);
            const data = fetchValidation(response);
            yield data && put({
                type: 'saveLogis',
                payload: data.body,
            });
        },

        * selectLogis({ payload }, { call, put }) {
            const response = yield call(queryLogisDetail, payload);
            const data = fetchValidation(response);
            yield data && put({
                type: 'show',
                payload: data.body,
            });
        },
    },

    reducers: {
        saveLogis(state, { payload }) {
            return {
                ...state,
                logisList: payload,
            };
        },

        show(state, { payload }) {
            return {
                ...state,
                dataInfo: payload,
            };
        },
    },
};

export default Model;
